
package com.bear.cmcc.NetTestHTTP.service;

import com.bear.cmcc.NetTestHTTP.component.PowerLock;
import com.bear.cmcc.NetTestHTTP.constant.MyCommonConstant;
import com.bear.cmcc.NetTestHTTP.util.MyCommonUtil;
import com.bear.cmcc.NetTestHTTP.util.NetTestUtil;
import com.bear.cmcc.NetTestHTTP.util.SetUtil;
import com.bear.cmcc.NetTestHTTP.util.TimeUtil;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.util.Log;

import java.util.Timer;
import java.util.TimerTask;

/**
 * 自动测试服务(这个服务不能有任何网络下载服务，要不然会造成网络测试服务测试不准问题)。
 * 
 * @author suchangjun
 */
public class AutoTestService extends Service {
    ;
    private final static String TAG = "AutoTestService";

    private int autoTestTime = MyCommonConstant.DEFAULT_AUTO_RUN_GAP * (1000 * 60);
    private int delay_time = 5 * (1000 * 60);//计划任务延迟5分钟开始，以防止这时候版本更新服务，如果启动测试服务，会把版本风险服务停止.

    /**
     * 自动运行服务器是否运行
     */
    private boolean isAutoServiceOn = true;

    private PowerLock powerLock;

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    public void onCreate() {
        super.onCreate();
        try {
            powerLock = new PowerLock(this, TAG);
            powerLock.acquireWakeLock();
            timerRunOneTime = TimeUtil.getRandomServiceRunTime();
            initializeParam();
            // 判断自动运行，默认是否需呀运行。
            if (isAutoServiceOn) {
                initializeTimerTask();
                timer.schedule(timerTask, delay_time, autoTestTime);//这边APP调用启动有可能这时候处于版本更新
            }
        } catch (Exception e) {
            if (e != null) {
                e.printStackTrace();
            }
        }
    }

    private void initializeParam() {
        isAutoServiceOn = SetUtil.getAutoTest(getBaseContext());// 获取是否自动自动服务
        autoTestTime = SetUtil.getAutoTestGap(getBaseContext()) * (1000 * 60);// 获取自动启动服务的时间间隔
    }

    @Override
    public void onStart(Intent paramIntent, int paramInt) {
        super.onStart(paramIntent, paramInt);
        Log.i(TAG, "AutoTestService start");

        try {
            if (paramIntent != null) {
                String aciton = paramIntent.getAction();
                // 如果是修改自动测试时间。
                if (MyCommonConstant.PrivateActionName.AUTO_RESET_TIME_GAP.equals(aciton)) {
                    initializeParam();
                    if (isAutoServiceOn) {
                        Log.i(TAG, "AutoTestService reset time gap ");
                        // 先把当前的timerTask取消
                        timerTask.cancel();
                        // 然后移除取消的task
                        timer.purge();
                        // 重新启动一个task
                        timerTask = null;
                        initializeTimerTask();
                        timer.schedule(timerTask, 0, autoTestTime);//这边是手动触发
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void onDestroy() {
        Log.i(TAG, "AutoTestService destroy");
        destroyTimerResource();
        if (powerLock != null) {
            powerLock.releaseWakeLock();
            powerLock = null;
        }
        super.onDestroy();
    }

    private void destroyTimerResource() {
        try {
            if (timer != null) {
                timer.cancel();
                timer = null;
            }
        } catch (Exception e) {
            if (e != null) {
                e.printStackTrace();
            }
        }

        try {
            if (timerTask != null) {
                timerTask.cancel();
                timerTask = null;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private Timer timer = new Timer();

    private TimerTask timerTask = null;

    private void initializeTimerTask() {

        try {
            if (timerTask != null) {
                timerTask.cancel();
                timerTask = null;
            }
        } catch (Exception e1) {
            e1.printStackTrace();
        }

        timerTask = new TimerTask() {

            @Override
            public void run() {
                try {
                    Log.i(TAG, "AutoTestService time again autoTestTime = " + autoTestTime
                            / (1000 * 60) + "分钟");
                    boolean isTestRun = MyCommonUtil.isServiceRun(getBaseContext(),
                            NetTestService.class.getName());
                    // 判断当前测试服务是否在运行,如果没有运行，就运行
                    if (!isTestRun && isShouldRun()) {
                        Log.i(TAG, "AutoTestService send start test common");
                        NetTestUtil.startNetTestService(getBaseContext(), 1,true);
                        SetUtil.setNetTestRuningState(false, getBaseContext());
                    }

                } catch (Exception e) {
                    if (e != null) {
                        e.printStackTrace();
                    }
                } finally {

                }

            }

        };
    }

    /**
     * 判断timer是否要运行，在[20:00,06:00] 这个区间 随机运行一次
     * 
     * @return
     */
    public boolean isShouldRun() {
        boolean isRun = true;
        int hour = TimeUtil.getCurrentHourOfDay();
        // [20:00,06:00] 这个区间
        if (hour > timerEnd && hour <= timerBegin) {
            isRun = false;
            if (timerRunOneTime == hour) {
                isRun = true;
            }
        }
        Log.i(TAG, "current time=" + hour + " isRun= " + isRun);
        return isRun;
    }

    int timerBegin = 6;// timer 运行的开始时间。

    int timerEnd = 20;// timer 运行的结束时间。（在晚上 20：00---06：00只是运行一次）

    int timerRunOneTime = 21;// 在晚上 20：00---06：00只是运行一次时间 这个时间是随机产生
}
